#coding:utf-8
from django.utils.encoding import smart_str



#二级域名中间键
class SubdomainMiddleware(object):
    def process_request(self, request):
        domain_arrs = request.get_host().split('.')
        if len(domain_arrs) == 3 and domain_arrs[0] == 'card':
            #来自微信api时不校验csrf
            #setattr(request, '_dont_enforce_csrf_checks', True)
            request.path_info = '/%s%s' % (domain_arrs[0], request.path)
        return None


#缓存view后需要根据cookie来判断是否登录
class SignMiddleware(object):
    def process_response(self, request, response):
        if request.user.is_authenticated() and not request.COOKIES.get('uinfo'):
            response.set_cookie('uinfo', request.user.id)

        return response


#获取客户端IP
class SetRemoteAddrFromForwardedFor(object):
    def process_request(self, request):
        try:
            real_ip = request.META['HTTP_X_FORWARDED_FOR']
        except KeyError:
            pass
        else:
            # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
            # Take just the first one.
            real_ip = real_ip.split(",")[0]
            request.META['REMOTE_ADDR'] = real_ip